package com.ruoyi.web.controller.thirdAPI;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WaterBill;
import com.ruoyi.system.domain.WaterMeter;
import com.ruoyi.system.domain.WaterUser;
import com.ruoyi.system.domain.WaterYcmeterDatahistory;
import com.ruoyi.system.domain.tax.FluxPressureData;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 创源水表 （采集频率 30分钟，上传周期 6小时）
 * @data 2025/10/17 13:24
 */
@Controller
@RequestMapping("/cyApi")
public class CYDataController {

    private static final Logger log = LoggerFactory.getLogger(CYDataController.class);
    @Autowired
    private IWaterInterfaceService waterInterfaceService;
    @Autowired
    private IWaterMeterService waterMeterService;
    @Autowired
    private IWaterUserService waterUserService;
    @Autowired
    private IWaterYcmeterDatahistoryService historyService;
    @Autowired
    private IWaterBillService waterBillService;

    @PostMapping("/pushData")
    @ResponseBody
    public String pushData(String meterNo,String readtime,Double flux,Double totalFlux,Double pressure){
        log.info("创源水表数据：{}",meterNo+"-"+readtime+"-"+flux+"-"+totalFlux+"-"+pressure);
        FluxPressureData fluxPressureData = new FluxPressureData();
        fluxPressureData.setMeterNo(meterNo);
        readtime = readtime.substring(0,13)+":00";  // 设置读数时间 为 整点
        fluxPressureData.setReadtime(readtime);
        fluxPressureData.setFlux(flux);
        fluxPressureData.setTotalFlux(totalFlux);
        fluxPressureData.setPressure(pressure);
        waterInterfaceService.pushCYWaterMeterData(fluxPressureData);
        return "success";
    }

    /**
     * 获取实时数据
     * @return
     */
    @PostMapping("/getRealData")
    @ResponseBody
    public List<WaterMeter> getRealData(){
        List<WaterMeter> list = new ArrayList<>();
        WaterMeter waterMeter = new WaterMeter();
        waterMeter.setMeterType("0");
        List<WaterMeter> meters = waterMeterService.selectWaterMeterList(waterMeter);
        for(WaterMeter meter : meters){
            if(StringUtils.isNotEmpty(meter.getReadDate())){
                list.add(meter);
            }
        }
        return list;
    }

    /**
     * 获取历史数据
     * @return
     */
    @PostMapping("/getHistoryData")
    @ResponseBody
    public List<WaterYcmeterDatahistory> getHistoryData(String meterNo){
        WaterYcmeterDatahistory dataHistory = new WaterYcmeterDatahistory();
        dataHistory.setMeterNo(meterNo);
        return historyService.selectWaterYcmeterDatahistoryList(dataHistory);
    }

    @PostMapping("/getUserList")
    @ResponseBody
    public List<WaterUser> getUserList(String userId){
        WaterUser waterUser = new WaterUser();
        waterUser.setUserId(userId);
        List<WaterUser> list = waterUserService.selectWaterUserList(waterUser);
        return list;
    }

    /**
     * 获取营收数据 接口
     * @return
     */
    @PostMapping("/getRevenueData")
    @ResponseBody
    public Map<String,Object> getRevenueData(){
        Map<String,Object> map = new HashMap<>();
        // 用户数量（即项目数）、表数量、上月收费金额
        WaterUser waterUser = new WaterUser();
        waterUser.setCompanyId("41007");
        List<WaterUser> list = waterUserService.selectWaterUserList(waterUser);
        long userCount = list.stream()
                .map(WaterUser::getAcceptCode)
                .filter(Objects::nonNull)  // 过滤null值
                .distinct()
                .count();
        WaterMeter waterMeter = new WaterMeter();
        Map<String,Object> meterParam = new HashMap<>();
        meterParam.put("meterState","3");
        waterMeter.setParams(meterParam);
        List<WaterMeter> meters = waterMeterService.selectWaterMeterList(waterMeter); // 查询所有正常的水表
        map.put("userCount",userCount);
        map.put("meterCount",meters.size());
        // 营收情况（月份-水费）
        List<WaterBill> billList = waterBillService.selectWaterBillList(new WaterBill());
        int currentYear = LocalDate.now().getYear();
        if(currentYear==2025){
            LocalDate startDate = LocalDate.of(2025, 1, 1);
            for(int i=0;i<=3;i++){
                LocalDate nextMonth = startDate.plusMonths(i);
                WaterBill bill = new WaterBill();
                bill.setMonth(nextMonth.format(DateTimeFormatter.ofPattern("yyyy-MM")));
                bill.setUsageAmount(0.0);
                bill.setTotalAmount(0.0);
                billList.add(bill);
            }
        }
        // 上月营收总览(抄表水量、应收金额、实收金额、欠费金额)
        // 用水量分析（月份-用水量）
        // 按月份自然排序统计月用水量
        Map<String, Double> waterVolumeMap = billList.stream()
                .collect(Collectors.groupingBy(
                        WaterBill::getMonth,
                        TreeMap::new,  // 使用TreeMap实现自动排序
                        Collectors.summingDouble(WaterBill::getUsageAmount)
                ));
        map.put("waterVolumeMap",waterVolumeMap);
        String lastWaterVolume = String.format("%.2f", StringUtils.getLastEntry(waterVolumeMap).getValue()/10000);
        // 按月份自然排序统计每月水费
        Map<String, Double> amountMap = billList.stream()
                .collect(Collectors.groupingBy(
                        WaterBill::getMonth,
                        TreeMap::new,  // 使用TreeMap实现自动排序
                        Collectors.summingDouble(WaterBill::getTotalAmount)
                ));
        map.put("amountMap",amountMap);
        String waterFee = StringUtils.getLastEntry(amountMap).getValue()+"";
        String lastWaterFee = String.format("%.2f", StringUtils.getLastEntry(amountMap).getValue()/10000);
        map.put("lastWaterVolume", lastWaterVolume); // 上月用水量
        map.put("lastWaterFee",lastWaterFee); // 上月水费（四舍五入后的）
        map.put("waterFee",waterFee); // 实际水费
        // 用户用水量排行榜
        List<WaterBill> billListByMonth = billList.stream()
                .filter(bill -> bill.getMonth().equals(StringUtils.getLastEntry(amountMap).getKey()))
                .collect(Collectors.toList());
        // 按用户分组统计用水量 分组统计并排序取前4
        Map<String, Double> userWaterVolumeMap = billListByMonth.stream()
                .filter(bill -> bill.getUserName() != null)  // 过滤掉userName为null的记录
                .collect(Collectors.groupingBy(
                        WaterBill::getUserName,
                        Collectors.summingDouble(WaterBill::getUsageAmount)
                ))
                .entrySet().stream()
                .sorted(Map.Entry.<String, Double>comparingByValue().reversed()) // 按用水量降序
                .limit(4) // 取前4个
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (e1, e2) -> e1,
                        LinkedHashMap::new // 保持排序顺序
                ));
        map.put("userWaterVolumeMap",userWaterVolumeMap);
        String lastMonth = StringUtils.getLastEntry(amountMap).getKey();
        map.put("lastMonth",lastMonth);
        // 水量区间分布
        int[] waterVolumeRange = new int[5];
        for(String month : waterVolumeMap.keySet()){
            double waterVolume = waterVolumeMap.get(month);
            if(waterVolume<=5000){
                waterVolumeRange[0]++;
            }else if(waterVolume>5000&&waterVolume<=10000){
                waterVolumeRange[1]++;
            }else if(waterVolume>10000&&waterVolume<=15000){
                waterVolumeRange[2]++;
            }else if(waterVolume>15000&&waterVolume<=20000){
                waterVolumeRange[3]++;
            }else if(waterVolume>20000){
                waterVolumeRange[4]++;
            }
        }
        List<String> volueRangeList = Arrays.asList("0-5000", "5000-10000", "10000-15000", "15000-20000", "20000以上");
        List<Map<String, Object>> rangeListMap = new ArrayList<>();
        for(int i=0;i<waterVolumeRange.length;i++){
            Map<String,Object> rangeMap = new HashMap<>();
            rangeMap.put("name",volueRangeList.get(i));
            rangeMap.put("value",waterVolumeRange[i]);
            rangeListMap.add(rangeMap);
        }
        map.put("rangeListMap",rangeListMap);
        // 水表状态分析
        List<WaterMeter> meterList = waterMeterService.selectWaterMeterList(new WaterMeter());
        Map<Integer, Long> meterStateMap = meterList.stream()
                .collect(Collectors.groupingBy(
                        WaterMeter::getMeterState,
                        Collectors.counting()
                ));
        List<Map<String, Object>> meterStateListMap = new ArrayList<>();
        for(int meterState : meterStateMap.keySet()){
            Map<String,Object> stateMap = new HashMap<>();
            if(meterState==0){
                stateMap.put("name","待用");
            }
            if(meterState==1){
                stateMap.put("name","安装");
            }
            if(meterState==2){
                stateMap.put("name","使用");
            }
            if(meterState==3){
                stateMap.put("name","停用");
            }
            if(meterState==4){
                stateMap.put("name","拆除");
            }
            stateMap.put("value",meterStateMap.get(meterState));
            meterStateListMap.add(stateMap);
        }
        map.put("meterStateListMap",meterStateListMap);
        // 报警事件（待定）
        return map;
    }

}
